package com.kaigejava;

import org.junit.jupiter.api.Test;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
 * @author 凯哥Java
 * @description
 * @company HDTD
 * @since 2023/4/17 15:38
 */
public class JsCallJava {
    @Test
    public void test(){
        String jsStr =  "function sum(c1,c2){\n" +
                "\t return c1+c2;\n" +
                "}";
        String ret = "";
        System.out.println(runJs(jsStr,"sum","1","2"));
    }

    /**
     * 执行JS函数，参数和返回值都是String类型
     * @param jsStr
     * @param func
     * @param parameter
     * @return
     */
    public String runJs(String jsStr,String func,String...parameter){
        String regular = jsStr;
        //创建引擎实例
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Object result = "";
        try {
            //编译
            engine.eval(regular);
            if (engine instanceof Invocable) {
                // 执行方法
                result = ((Invocable) engine).invokeFunction(func, parameter);
                return String.valueOf(result);
            }
        } catch (Exception e) {
            return "表达式runtime错误:" + e.getMessage();
        }
        return "";
    }
}
